<script setup>
// https://juejin.cn/post/7261972803695624250
import { ref } from 'vue'

import { useToggle } from '@vueuse/shared'
import { useFetch } from '@vueuse/core'

const url = ref('https://httpbin.org/get')
const refetch = ref(false)

const toggleRefetch = useToggle(refetch)

const { data, error, abort, statusCode, isFetching, isFinished, canAbort, execute } = useFetch(
  url,
  { refetch, immediate: false }
).get()
</script>

<template>
  <div>
    <div>
      <div>以下URL可用于测试useFetch的不同功能</div>
      <div class="mt-2">
        普通请求：
        <code> https://httpbin.org/get </code>
      </div>
      <div>
        中止请求：
        <code> https://httpbin.org/delay/10 </code>
      </div>
      <div>
        响应错误：
        <code> http://httpbin.org/status/500 </code>
      </div>
    </div>

    <input v-model="url" type="text" />
    <button @click="execute">执行</button>
    <button @click="toggleRefetch">
      <span class="ml-2">{{ refetch ? '重新获取已开启' : '重新获取已关闭' }}</span>
    </button>
    <button v-if="canAbort" class="orange" @click="abort">中止</button>
    <pre class="code-block">
      data:{{ data }}-error:{{ error }}-statusCode:{{ statusCode }}-isFetching:{{ isFetching }}-isFinished:{{ isFinished }}-canAbort:{{ canAbort }}
    </pre>
  </div>
</template>
